﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO.Ports;

namespace HardwareLibrary.ComLibrary
{
    public class ComHelper
    {
        public SerialPort sPort;
        public string whatRecieved;//接收字符串

        #region "串口操作方法"
        public virtual bool OpenComPortNoEvent(int iPortNum, int iBaudRate)
        {
            try
            {
                if (sPort == null)
                {
                    sPort = new SerialPort();
                    sPort.PortName = "COM" + iPortNum;
                    sPort.BaudRate = iBaudRate;
                    sPort.Open();
                }
                return sPort.IsOpen;
            }
            catch
            {
                return sPort.IsOpen;
            }
        }
        public virtual bool OpenComPortNoEvent(int iPortNum, string strComParam)
        {
            try
            {
                if (sPort == null)
                {
                    sPort = new SerialPort();
                    sPort.PortName = "COM" + iPortNum;
                    string[] str = strComParam.Split(',');
                    sPort.BaudRate = Convert.ToInt32(str[0]);
                    switch (str[1])
                    {
                        case "N":
                            sPort.Parity = Parity.None;
                            break;
                        case "O":
                            sPort.Parity = Parity.Odd;
                            break;
                        case "E":
                            sPort.Parity = Parity.Even;
                            break;
                        case "M":
                            sPort.Parity = Parity.Mark;
                            break;
                        case "S":
                            sPort.Parity = Parity.Space;
                            break;
                    }
                    sPort.DataBits = Convert.ToInt32(str[2]);
                    switch (str[3])
                    {
                        case "0":
                            sPort.StopBits = StopBits.None;
                            break;
                        case "1":
                            sPort.StopBits = StopBits.One;
                            break;
                        case "2":
                            sPort.StopBits = StopBits.Two;
                            break;
                        case "3":
                            sPort.StopBits = StopBits.OnePointFive;
                            break;
                    }
                    sPort.Open();
                }
                return sPort.IsOpen;
            }
            catch
            {
                return sPort.IsOpen;
            }
        }
        /// <summary>
        /// 打开串口,带事件触发
        /// </summary>
        /// <param name="iPortNum">端口号,如COM1为1，Com2为2</param>
        /// <param name="iBaudRate">波特率，如9600</param>
        /// <returns>返回打开是否成功,Ture表示打开成功，False表示打开失败</returns>
        public virtual bool OpenComPortWithEventHandler(int iPortNum, int iBaudRate)
        {
            bool OpenFlag = OpenComPortNoEvent(iPortNum, iBaudRate);
            if (OpenFlag == true)
            {
                sPort.DataReceived += new SerialDataReceivedEventHandler(Port_DataReceived);
            }
            return OpenFlag;
        }
        /// <summary>
        /// 打开串口，带事件触发
        /// </summary>
        /// <param name="iPortNum">端口号,如COM1为1，Com2为2</param>
        /// <param name="strComParam">端口参数:如9600,N,8,1</param>
        /// <returns>返回打开是否成功,Ture表示打开成功，False表示打开失败</returns>
        public virtual bool OpenComPortWithEventHandler(int iPortNum, string strComParam)
        {
            bool OpenFlag = OpenComPortNoEvent(iPortNum, strComParam);
            if (OpenFlag == true)
            {
                sPort.DataReceived += new SerialDataReceivedEventHandler(Port_DataReceived);
            }
            return OpenFlag;
        }
        /// <summary>
        /// 端口数据接收触发事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public virtual void Port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            whatRecieved = sPort.ReadExisting();
        }
        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="sendStr">发送内容</param>
        public virtual void SendData(string sendStr)
        {
            sPort.Write(sendStr);
        }
        /// <summary>
        /// 发送一行数据
        /// </summary>
        /// <param name="sendStr">发送内容，自动换行符会自动输入到发送端口中</param>
        public virtual void SendDataLine(string sendStr)
        {
            sPort.WriteLine(sendStr);
        }
        /// <summary>
        /// 关闭端口
        /// </summary>
        /// <returns></returns>
        public virtual bool CloseComPort()
        {
            try
            {
                if (sPort != null)
                {
                    sPort.Close();
                    if (sPort.IsOpen == false)
                    {
                        sPort.DataReceived -= new SerialDataReceivedEventHandler(Port_DataReceived);
                        sPort = null;
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return true;
                }
            }
            catch
            {
                return sPort.IsOpen;
            }
        }
        /// <summary>
        /// 获取端口接收的完整字符串
        /// </summary>
        /// <returns></returns>
        public virtual string GetPortValue()
        {
            if (sPort == null)
            {
                return "";
            }
            else
            {
                return "" + whatRecieved;
            }
        }
        #endregion
    }
}
